//
//  OYComposeView.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/8.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import UIKit
import pop

class OYComposeView: UIView {

     // MARK: -控件懒加载
    lazy var imageView:UIImageView = UIImageView()
    lazy var buttonArr:[OYComposeButton] = [OYComposeButton]()
    var target:UIViewController?
    lazy var composeBtnList:[OYComposeBtnModel] = [OYComposeBtnModel]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        
        setupUI()
    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    
        popAnimation(isUp: false)
        
        DispatchQueue.main.asyncAfter(deadline:DispatchTime.now() + 0.3) {
            self.removeFromSuperview()

        }
    }
    
    func setupUI() {
     
        
        addSubview(imageView)
        
         // MARK: -加载button类型的数据
        loadPlistData()
        
        imageView.snp_makeConstraints { (make) in
            make.top.equalTo(self)
            make.leading.equalTo(self)
            make.size.equalTo(self)
        }
        imageView.image = screenShot().applyLightEffect()
        
        
        let buttonW:CGFloat = 80
        let buttonH:CGFloat = 100
        
        for i in 0..<6 {
            let button = OYComposeButton()
            button.tag = i
            
            let buttonMargin = (ScreenWidth - buttonW * 3) / 4
            
            let coloum: Int = i % 3
            let row: Int = i / 3
            
            
            button.x = CGFloat(coloum + 1) * buttonMargin + CGFloat(coloum) * buttonW
            button.y = ScreenHeight + CGFloat(row) * (buttonMargin + buttonH)
            button.size = CGSize(width: buttonW, height: buttonH)
            
            button.setTitle(composeBtnList[i].title, for: .normal)
            button.setImage(UIImage(named:composeBtnList[i].icon!), for: .normal)
            
            button.addTarget(self, action: #selector(buttonClickAction(sender:)), for: .touchUpInside)
            addSubview(button)

            buttonArr.append(button)

        }
        
        popAnimation(isUp: true)
    }
    
    
    /// 点击button响应事件
    func buttonClickAction(sender:UIButton) {
        
        UIView.animate(withDuration: 0.25, animations: {
            
            // 遍历button数组。如果是当前button放大，如果不是缩小
            for button in self.buttonArr {
                if button == sender {
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                } else {
                    button.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
            }
            
        }) { (_) in
            
            //动画完成之后恢复原来大小
            for button in self.buttonArr {
                UIView.animate(withDuration: 0.2, animations: {
                    
                    button.transform = CGAffineTransform.identity
                    
                }, completion: { (_) -> Void in
                    
                     // MARK: -点击button动画完成，进行modal
                    
                    let model: OYComposeBtnModel = self.composeBtnList[button.tag]
                    let cls = NSClassFromString(model.className!) as! UIViewController.Type
                    // 根据model中的类名创建将要跳转到的控制器
                    let vc = cls.init()
                    let navVc = OYNavigationController(rootViewController: vc)
                    self.target?.present(navVc, animated: true, completion: {
                        self.removeFromSuperview()
                    })
                })
            }
        }
        
        
    }
    
     // MARK: -获取MainController进行modal
    func show (target:UIViewController) {
        self.target = target
        
        target.view.addSubview(self)
    }
    
     // MARK: -pop动画
    func popAnimation(isUp:Bool)->() {
        if isUp == false {
            buttonArr.reverse()
        }
        
        for (i,button) in buttonArr.enumerated() {
            let popSpringAni = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            if isUp {
                popSpringAni?.toValue = CGPoint(x: button.centerX, y: button.centerY - 350)

            }else {
                popSpringAni?.toValue = CGPoint(x: button.centerX, y: button.centerY + 350)

            }
            
            popSpringAni?.springBounciness = 10
            popSpringAni?.springSpeed = 10
            popSpringAni?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            
            button.pop_add(popSpringAni, forKey: "buttomSpringAni")
        }
    }
    
    /// 截取跳转前屏幕的图片
    ///
    /// - Returns: 返回截取到的图片
    func screenShot ()->(UIImage) {
    
        // 获取图片上下文
        let window = UIApplication.shared.keyWindow!
        UIGraphicsBeginImageContext(window.frame.size)
        
        // 截屏
        window.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: window.size), afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //关闭图片上下文
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    
    func loadPlistData () {
        
        let plistUrl:URL = Bundle.main.url(forResource: "compose.plist", withExtension: nil)!
        let plistArr:[[String:Any]] = NSArray.init(contentsOf: plistUrl) as! [[String:Any]]
        
        let modelArr: [OYComposeBtnModel] = NSArray.yy_modelArray(with: OYComposeBtnModel.self, json: plistArr) as! [OYComposeBtnModel]
        
        composeBtnList = modelArr
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
}
